﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;

namespace ImobitechDao.Repositories
{
     public abstract class BaseRepository<T> : IBaseRepository<T> where T : EntityObject, IEntityWithId
    {
        public BaseRepository(ImobitechEntities context)
        {
            _context = context;
        }

        protected ImobitechEntities _context;

        protected abstract string TableName { get; }
        protected abstract string EntitySetName { get; }

        #region IBaseRepositoy<T> Members
        public virtual T GetById(int id)
        {
            return (from e in _context.CreateQuery<T>(this.TableName)
                    where e.Id == id
                    select e).FirstOrDefault();

        }

        public virtual List<T> GetAll()
        {
            return (from e in _context.CreateQuery<T>(this.TableName)
                    select e).ToList();
        }

        public virtual List<T> GetAll(string ColumnOrder)
        {
            return (from e in _context.CreateQuery<T>(this.TableName)
                    orderby ColumnOrder
                    select e).ToList();
        }
        
        public virtual Object Create(T entity)
        {
            _context.AddObject(this.TableName, entity);
            _context.SaveChanges();
            return true;
        }

        public virtual Object Update(T entity)
        {
            try
            {
                _context.Update(this.EntitySetName, entity);
                _context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public virtual Object Delete(int id)
        {
            var entity = this.GetById(id);
            _context.DeleteObject(entity);
            _context.SaveChanges();
            return true;
        }
        #endregion
    }
}